package com.xiongwei.dateAndTime;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeoutException;

/**
 * 在处理日期和时间时,尽量使用新的java.time包;
 * 在数据库中存储时间戳时,尽量使用long型时间戳,它具有省空间,效率高,不依赖数据库的优点
 *
 * @author XiongWei
 * @date 2021/1/30
 */
public class OldDateToNewDate {

    public static void main(String[] args) {
        /*
        旧API转新API
         */
        //Date -> Instant
        Instant instant = new Date().toInstant();
        System.out.println(instant);

        //Calendar -> Instant -> ZonedDateTime
        Calendar c = Calendar.getInstance();
        Instant instant2 = c.toInstant();
        ZonedDateTime zonedDateTime = instant2.atZone(c.getTimeZone().toZoneId());
        System.out.println(zonedDateTime);

        /*
        新API转旧API
         */
        //zonedDateTime -> Long
        ZonedDateTime zdt = ZonedDateTime.now();
        long ts = zdt.toEpochSecond() * 1000;

        //Long -> Date
        Date date = new Date(ts);

        //LONG -> Calendar
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.setTimeZone(TimeZone.getTimeZone(zdt.getZone().getId()));
        calendar.setTimeInMillis(zdt.toEpochSecond() * 1000);

        /*
        java.sql.Date继承自java.util.Date,但会忽略所有时间相关的信息
        存储一个long型时间戳，我们可以编写一个timestampToString()的方法，
        非常简单地为不同用户以不同的偏好来显示不同的本地时间
         */
        long ls = 1574208900000L;
        System.out.println(timeStampToString(ls, Locale.CHINA, "Asia/Shanghai"));
        System.out.println(timeStampToString(ls, Locale.US, "America/New_York"));
    }

    static String timeStampToString(Long epochMilli, Locale lo, String zoneId) {
        Instant instant = Instant.ofEpochMilli(epochMilli);
        DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT);
        return formatter.withLocale(lo).format(ZonedDateTime.ofInstant(instant, ZoneId.of(zoneId)));
    }
}
